package cn.doctor.assistant.pad.api;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by jiaolf on 2016/4/14.
 * 上传图片的接口
 */
public class UploadPictureAPI {
    // 上传路径
    private static final String URL_DOMAIN = "http://101.201.148.249/doctorx/upload/uploadImage";

    public static void uploadPic(String picPath, final AjaxCallBack<String> callBack) {

        RequestParams params = new RequestParams();
        params.addBodyParameter("file", new File(picPath));
        HttpUtils http = new HttpUtils();

        http.send(HttpRequest.HttpMethod.POST, URL_DOMAIN, params,
                new RequestCallBack<String>() {
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (callBack != null) {
                            callBack.onLoading(total, current);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        try {
                            JSONObject jsonObject = new JSONObject(responseInfo.result);
                            boolean success = jsonObject.getBoolean("success");
                            if(success){
                                String data =  jsonObject.getString("data");
                                callBack.onSuccess(data);
                            }else {
                                callBack.onFailure(null, 0, "上传失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        if (callBack != null) {
                            callBack.onFailure(null, 0, s);
                        }
                    }
                });

    }

}
